<template>
  <Breadcrumb>
    <span class="btn search" @click="search">查询</span>
    <span class="btn reset" @click="reset">重置</span>
    <span class="btn add" @click="add">新增</span>
  </Breadcrumb>
  <SearchForm :model="data.queryParams">
    <el-form-item label="用户账号">
      <el-input v-model="data.queryParams.account" clearable />
    </el-form-item>
    <el-form-item label="用户姓名">
      <el-input v-model="data.queryParams.name" clearable />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="data.queryParams.phone" clearable />
    </el-form-item>
    <el-form-item label="用户状态">
      <el-select v-model="data.queryParams.status" clearable>
        <el-option v-for="item in SysUserStatus" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
  </SearchForm>
  <SimpleTable ref="simpleTable" :_configs="configs" :_data="data.dataList" :_total="data.total" @_load="loadData">
    <template #opt>
      <el-table-column v-slot="{ row }" prop="opt" label="操作" width="200">
        <span class="link edit" @click="activeUser(row)">{{ row.status === 0 ? '激活' : '注销' }}</span>
        <span class="link edit" @click="edit(row)">编辑</span>
        <span class="link edit" @click="resetPassword(row)">重置密码</span>
        <span class="link edit" @click="del(row)">删除</span>
      </el-table-column>
    </template>
  </SimpleTable>
  <SimpleDialog v-model="addForm.dialogShow" :close-on-click-modal="false" :destroy-on-close="true" :close="cancel" width="600px">
    <template #header><span>{{ addForm.dialogTitle }}</span></template>
    <template #default>
      <el-form
          ref="addUserForm"
          label-position="right"
          label-width="100px"
          :rules="addUserFormRules"
          :model="addForm.formParams"
      >
        <el-form-item label="用户账号" prop="account" required>
          <el-input v-model="addForm.formParams.account" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name" required>
          <el-input v-model="addForm.formParams.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" required>
          <el-input v-model="addForm.formParams.phone" />
        </el-form-item>
        <el-form-item v-if="addForm.formType === 1" label="密码" prop="password" required>
          <el-input type="password" v-model="addForm.formParams.password" />
        </el-form-item>
        <el-form-item v-if="addForm.formType === 1" label="确认密码" prop="confirmPassword" required>
          <el-input type="password" v-model="addForm.formParams.confirmPassword" />
        </el-form-item>
        <el-form-item label="超级管理员" prop="superUser" required>
          <el-radio-group v-model="addForm.formParams.superUser">
            <el-radio :label="0" size="large">否</el-radio>
            <el-radio :label="1" size="large">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addForm.formParams.superUser === 0" label="关联角色" prop="roleIds" required>
          <el-select
              multiple
              v-model="addForm.formParams.roleIds"
              placeholder="请选择用户角色"
              size="large"
          >
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.formParams.email" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="btn cancel" @click="cancel(addUserForm)">取消</span>
      <span class="btn confirm" @click="confirm(addUserForm)">确认</span>
    </template>
  </SimpleDialog>
</template>

<script lang="ts" setup>
import Breadcrumb from 'components/back/common/Breadcrumb.vue'
import SearchForm from 'components/back/SearchForm/Index.vue'
import SimpleTable from 'components/back/SimpleTable/Index.vue'
import SimpleDialog from 'components/back/SimpleDialog/Index.vue'
import { SysUserStatus } from "@/api/User"
import type { FormInstance, FormRules } from "element-plus"
import { validatePhone, clearObjectFields } from '@/utils/helpers'

const { proxy }: any = getCurrentInstance()

const simpleTable = ref()
const configs = [
  {
    prop: 'account',
    label: '用户账号'
  },
  {
    prop: 'name',
    label: '用户姓名'
  },
  {
    prop: 'phone',
    label: '手机号'
  },
  {
    prop: 'email',
    label: '邮箱'
  },
  {
    prop: 'createTime',
    label: '创建时间'
  },
  {
    prop: 'status',
    label: '用户状态',
    formatter: (row: any, value: any) => {
      if (0 === row.status) return '未激活'
      if (1 === row.status) return '已激活'
      if (9 === row.status) return '已删除'
    }
  }
]

const data = reactive({
  queryParams: {
    account: undefined,
    name: undefined,
    phone: undefined,
    status: undefined
  },
  total: 0,
  dataList: []
})

const addUserForm = ref()

const addForm = reactive({
  dialogShow: false,
  formType: 1,
  dialogTitle: '',
  formParams: {
    id: void 0,
    account: void 0,
    name: void 0,
    phone: void 0,
    password: void 0,
    confirmPassword: void 0,
    superUser: 0,
    roleIds: Array<number>(),
    email: void 0
  }
})

const validateAccount = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入用户账号！'))
  } else if (value.length && (value.length < 4 ||  value.length > 20)) {
    callback(new Error("账号长度需在4到20之间!"))
  } else {
    callback()
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码！'))
  } else if (value.length && (value.length < 3 ||  value.length > 20)) {
    callback(new Error("密码长度需在3到20之间!"))
  } else {
    callback()
  }
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入确认密码！'))
  } else if (value !== addForm.formParams.password) {
    callback(new Error("确认密码需要与密码一致!"))
  } else {
    callback()
  }
}

const addUserFormRules = reactive<FormRules>({
  account: [
    { validator: validateAccount, trigger: '' }
  ],
  name: [
    { required: true, message: '请输入用户姓名！', trigger: '' }
  ],
  phone: [
    { validator: validatePhone, trigger: '' }
  ],
  password: [
    { validator: validatePassword, trigger: '' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: '' }
  ]
})

const search = () => {
  simpleTable.value._init()
}

const reset = () => {
  data.queryParams.account = undefined
  data.queryParams.name = undefined
  data.queryParams.phone = undefined
  data.queryParams.status = undefined
}

const resetAddForm = () => {
  clearObjectFields(addForm.formParams)
}

const add = () => {
  resetAddForm()
  addForm.dialogTitle = '添加用户'
  addForm.formType = 1
  addForm.formParams.superUser = 0
  addForm.formParams.roleIds = []
  addForm.dialogShow = true
}

const edit = (row: any) => {
  resetAddForm()
  Promise.resolve(
    proxy.$API.userApi.queryUserRole({ userId: row.id }).then((res: any) => {
      addForm.formParams.roleIds = res ?? []
    })
  ).then(() => {
    addForm.dialogTitle = '编辑用户'
    addForm.formType = 2
    addForm.formParams.id = row.id
    addForm.formParams.account = row.account
    addForm.formParams.name = row.name
    addForm.formParams.phone = row.phone
    addForm.formParams.superUser = row.superUser
    addForm.formParams.email = row.email
    addForm.dialogShow = true
  })
}

const activeUser = (row: any) => {
  let { id, status } = row
  status = 0 === status ? 1 : 0
  proxy.$API.userApi.updateSysUser({ id, status }).then((res: any) => {
    if (res.code && res.code === 10000) {
      ElMessage.success('操作成功！')
      search()
    } else {
      ElMessage.error(res.msg || '操作失败！')
    }
  })
}

const resetPassword = (row: any) => {
  proxy.$API.userApi.resetSysUserPassword({ id: row.id }).then((res: any) => {
    if (res.code && res.code === 10000) {
      ElMessage.success('重置成功！')
    } else {
      ElMessage.error(res.msg || '重置失败！')
    }
  })
}

const del = (row: any) => {
  ElMessageBox.confirm('确认删除该用户？', '通知', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    let id = row.id
    proxy.$API.userApi.deleteSysUser({ id }).then((res: any) => {
      if (res.code && res.code === 10000) {
        ElMessage.success('删除成功！')
        search()
      } else {
        ElMessage.error(res.msg || '删除失败！')
      }
    })
  }).catch(() => {})
}

const cancel = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields()
  }
  addForm.dialogShow = false
}

const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (addForm.formType === 1) {
    await formEl.validate((valid, fields) => {
      if (valid) {
        let { account, name, phone, password, email, superUser, roleIds } = addForm.formParams
        proxy.$API.userApi.insertSysUser({ account, name, phone, password, email, superUser, roleIds }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('添加成功！')
            addForm.dialogShow = false
            search()
          } else {
            ElMessage.error(res.msg || '添加失败！')
          }
        })
      }
    })
  } else {
    await formEl.validate((valid, fields) => {
      if (valid) {
        let { id, account, name, phone, email, superUser, roleIds } = addForm.formParams
        proxy.$API.userApi.updateSysUser({ id, account, name, phone, email, superUser, roleIds }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('编辑成功！')
            addForm.dialogShow = false
            search()
          } else {
            ElMessage.error(res.msg || '编辑失败！')
          }
        })
      }
    })
  }
}

const loadData = (pageNum: number, pageSize: number) => {
  proxy.$API.userApi.querySysUserPage({ ...data.queryParams, pageNum, pageSize }).then((res: any) => {
    data.dataList = res.records ?? []
    data.total = res.total ?? 0
  })
}

let roleList = []

const loadRoleList = () => {
  proxy.$API.systemApi.querySysRole({}).then((res: any) => {
    roleList = res.records ?? []
  })
}

onMounted(() => {
  loadRoleList()
})

</script>

<style lang="less" scoped>

</style>
